<template>
  <div>
    <el-dialog :title="id?'编辑配置':'新增配置'" v-if="dialogFormVisible" v-model="dialogFormVisible" width="1300px">
        <span style="color:red">{{errorTips}}</span>
        <el-tabs  v-model="activeName" v-loading="loading">
        <el-tab-pane label="基本信息" name="basic">
            <basic ref="basicRef" :formList="formListArr||[]" :formKey="formKey" :basic="json.basic"
            @setFormKeyAndColumns="setFormKeyAndColumns" @setJson="setJson"/>
        </el-tab-pane>

        <el-tab-pane label="导入表设置" name="main">
            <main-set ref="mainRef" :formKey="formKey" :main="json.main" :formColumns="formColumns" :primaryKeyFieldObj="primaryKeyFieldObj" @setJson="setJson" />
        </el-tab-pane>
        <el-tab-pane label="关联表设置" name="relevance">
            <relevance ref="relevanceRef" :relevance="json.relevance" :relevanceFormKey="relevanceFormKey" :formColumns="formColumns"
            :primaryKeyFieldObj="primaryKeyFieldObj"  @setJson="setJson" />
        </el-tab-pane>
        </el-tabs>
        <template #footer>
            <span class="dialog-footer">
            <el-button @click="dialogFormVisible = false" :loading="loading">取 消</el-button>
            <el-button type="primary"  @click="getDataFromTabs" :loading="loading">保 存</el-button>
            </span>
        </template>
  </el-dialog>
  </div>
</template>
<script setup name='AddDialog'>
  import {
    formList
  } from "@/api/tool/formManage";
  import {
    saveOrUpdate
  } from "@/api/tool/importExport";
	import { ElMessage } from 'element-plus'
  import basic from "./basic.vue";
  import mainSet from "./mainSet.vue";
  import relevance from "./relevance.vue";
  const { proxy } = getCurrentInstance();
  const emits = defineEmits(['getList']);

   const dialogFormVisible =$ref(false),
        id = $ref(null),
        loading= $ref(false),
        activeName= $ref('basic'),
        formListArr= $ref(null),
        formKey= $ref(undefined), //主表
        relevanceFormKey= $ref(undefined), //关联表
        primaryKeyFieldObj=$ref({}),//表的主键
        formColumns= $ref({}), //字段
        tabsData=$ref({}),
        json=$ref({}),
        errorTips=$ref('');

   function open(data){
    dialogFormVisible=true
    activeName='basic'
           loading = true
        setTimeout(() => {
           loading = false
        }, 1000)
        
          id= null,
          formKey= undefined //主表
          relevanceFormKey= undefined //关联表
          json= {}
        if (!formListArr) {
          //获取表单列表
          getFormList()
        }
        if (data) {
          id = data.id
          formKey = data.formKey
          relevanceFormKey = data.relevanceFormKey
          let jsonData = JSON.parse(data.json),
            basic={
            configKey:data.configKey,
            configName:data.configName,
            remark:data.remark,
            configType:data.configType,
            formKey: data.formKey,
            relevanceFormKey:jsonData.relevance.formKey,
            relevanceConditions:jsonData.relevance.relevanceConditions,
          };
          json={...jsonData,basic}
          console.log(json)
        }
        dialogFormVisible = true
   }

   //获取表单列表
   function getFormList() {
        formList().then(res => {
          if (res.code == 200) {
            formListArr = res.data.map(item => {
              item.name = `${item.formTitle}(${item.formKey})`
              return item
            });
          }
        })
      }

    //获取tabs的数据
    function getDataFromTabs() {
        loading = true
        tabsData = {}
        errorTips = ''
        nextTick(() => {
          proxy.$refs['basicRef'].submit()
          proxy.$refs['mainRef'].submit()
          proxy.$refs['relevanceRef'].submit()
          setTimeout(() => {
            if (Object.keys(tabsData).length < 3) {
              loading = false
              errorTips = '请完善：'
              if (!tabsData.basic) {
                errorTips += '基本信息，'
              }
              if (!tabsData.main) {
                errorTips += '导入表设置，'
              }
              if (!tabsData.relevance) {
                errorTips += '关联表设置，'
              }
              errorTips = errorTips.substring(0, errorTips.length - 1)
            }
          }, 1000)
        })
      }
       //设置key和字段列表
    function setFormKeyAndColumns(obj) {
        formKey = obj.formKey
        relevanceFormKey = obj.relevanceFormKey
        formColumns = obj.formColumns
        primaryKeyFieldObj = obj.primaryKeyFieldObj
    }

    function setJson(data) {
        tabsData[data.tabType] = data.formData
        if (Object.keys(tabsData).length == 3) {
          let titles=[],
              errorTips='，';
          tabsData.main.list.forEach(item=>{
            if(item.checked){
              const title=item.aliasTitle||item.columnTitle
              if(titles.indexOf(title)>-1&&errorTips.indexOf('，'+title+'，')<0){
                errorTips+=title+'，'
              }
              titles.push(title)
            }
          })
          if(tabsData.relevance.list){
            tabsData.relevance.list.forEach(item=>{
              if(item.checked){
                const title=item.aliasTitle||item.columnTitle
                if(titles.indexOf(title)>-1&&errorTips.indexOf('，'+title+'，')<0){
                  errorTips+=title+'，'
                }
                titles.push(title)
              }
            })
          }
          if(errorTips.length>1){
            errorTips='存在相同标题：'+errorTips.substring(1, errorTips.length - 1)
            loading = false
            return
          }
          save()
        }
      }
      function save(){
         const data={
           "id": id,
           "configKey": tabsData.basic.configKey,
           "configName": tabsData.basic.configName,
           "formKey": tabsData.basic.formKey,
           "remark": tabsData.basic.remark,
           "configType": tabsData.basic.configType,
           "json": JSON.stringify({
               main:tabsData.main,
               relevance:{
                 formKey:tabsData.basic.relevanceFormKey,
                 relevanceConditions:tabsData.basic.relevanceConditions,
                 list:tabsData.relevance.list,
                 primaryKeyConditions:tabsData.relevance.primaryKeyConditions,
               }
             })
         }
          saveOrUpdate(data).then(res => {
            if (res.code == 200) {
			ElMessage({
				message: '保存成功',
				duration: 2000,
				showClose: true,
				type: 'success'
			}) 
              dialogFormVisible = false
              emits('getList')
            }
          }).finally(() => {
            loading = false
          })
      }
      
   defineExpose({
    open,
    });
</script>
<style lang="scss" scoped>

</style>
